<template>
  <div class="rider-order-detail">

    <!-- 订单状态头部 -->
    <div class="status-header">
      <div class="status-info">
        <div class="status-text">{{ getStatusText(orderInfo.status) }}</div>
        <div class="status-desc">{{ getStatusDesc(orderInfo.status) }}</div>
      </div>
      <div class="order-amount">¥{{ orderInfo.totalAmountStr }}</div>
    </div>

    <!-- 订单基本信息 -->
    <div class="order-basic">
      <div class="section-title">订单信息</div>
      <div class="info-row">
        <span class="label">订单编号</span>
        <span class="value text-ellipsis">{{ orderInfo.orderNo }}</span>
      </div>
      <div class="info-row">
        <span class="label">下单时间</span>
        <span class="value">{{ orderInfo.createTime }}</span>
      </div>
      <div class="info-row" v-if="orderInfo.singleNumber">
        <span class="label">取餐码</span>
        <span class="value pickup-code">{{ orderInfo.singleNumber }}</span>
      </div>
    </div>

    <!-- 商家信息 -->
    <div class="shop-info">
      <div class="section-title">商家信息</div>
      <div class="shop-card">
        <img class="shop-avatar" :src="orderInfo.storeAvatar || '../static/imgs/banner.png'" alt="">
        <div class="shop-detail">
          <div class="shop-name">{{ orderInfo.shopName }}</div>
          <div class="shop-address">{{ orderInfo.storeAddress }}</div>
        </div>
      </div>
    </div>

    <!-- 配送信息 -->
    <div class="delivery-info">
      <div class="section-title">配送信息</div>
      <div class="address-card">
        <div class="address-item">
          <div class="address-tag pickup-tag">取</div>
          <div class="address-content">
            <div class="address-text">{{ orderInfo.shopAddress }}</div>
          </div>
        </div>
        <div class="address-line"></div>
        <div class="address-item">
          <div class="address-tag delivery-tag">送</div>
          <div class="address-content">
            <div class="customer-name">{{ orderInfo.deliveryName }}</div>
            <div class="address-text">{{ orderInfo.deliveryAddress }}</div>
            <div class="customer-phone">{{ formatPhoneNumber(orderInfo.deliveryPhone) }}</div>
          </div>
          <div class="contact-btn" @click="contactCustomer" v-if="orderInfo.deliveryPhone&&isPhone">
            <span>📞</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品信息 -->
    <div class="goods-info">
      <div class="section-title">商品明细</div>
      <div class="goods-list">
        <div v-for="item in orderInfo.orderGoodsList" :key="item.id" class="goods-item">
          <img class="goods-image" :src="item.thumbnail" alt="">
          <div class="goods-detail">
            <div class="goods-name">{{ item.goodsName }}</div>
            <div class="goods-spec" v-if="item.skuDesc">{{ item.skuDesc }}</div>
            <div class="goods-priceStr">¥{{ item.priceStr }} × {{ item.goodsNum }}</div>
          </div>
        </div>
      </div>

      <div class="fee-summary">
        <!-- <div class="fee-row">
          <span class="fee-label">商品小计</span>
          <span class="fee-value">¥{{ orderInfo.goodsAmount }}</span>
        </div> -->
        <div class="fee-row">
          <span class="fee-label">配送费</span>
          <span class="fee-value">¥{{ orderInfo.customerDistributionFeeStr || '0.00' }}</span>
        </div>
        <div class="fee-row">
          <span class="fee-label">服务费</span>
          <span class="fee-value">¥{{ orderInfo.actualPayAmountStr || '0.00' }}</span>
        </div>
        <div class="fee-row">
          <span class="fee-label">打包费</span>
          <span class="fee-value">¥{{ orderInfo.needPayAmountStr || '0.00' }}</span>
        </div>
        <div class="fee-row total">
          <span class="fee-label">实付金额</span>
          <span class="fee-value">¥{{ orderInfo.totalAmountStr }}</span>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section" v-if="showActions">
      <template v-if="orderInfo.status === '3'">
        <button class="action-btn secondary" @click="contactCustomer">
          联系顾客
        </button>
        <button class="action-btn primary" @click="confirmDelivery">
          确认送达
        </button>
      </template>
    </div>

    <!-- 拍照弹窗 -->
    <wd-popup v-model="showPhotoDialog" position="center">
      <view class="photo-dialog">
        <view class="dialog-title">
          {{ currentAction === 'pickup' ? '取货凭证' : '送达凭证' }}
        </view>
        <view class="photo-area">
          <view class="photo-list">
            <view v-for="(photo, index) in photoList" :key="index" class="photo-item">
              <image :src="photo.serverUrl || photo.localPath" mode="aspectFill" />
            </view>
            <view class="photo-add" @click="handleTakePhoto" v-if="photoList.length < 3">
              <text class="iconfont icon-camera"></text>
              <text>拍照</text>
            </view>
          </view>
        </view>
        <view class="remarks-area">
          <textarea v-model="remarks" placeholder="请输入备注信息" class="remarks-input" />
        </view>
        <view class="dialog-footer">
          <button @click="showPhotoDialog = false" class="btn-cancel">取消</button>
          <button @click="submitPhotoAndRemarks" class="btn-submit">确定</button>
        </view>
      </view>
    </wd-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Return from '@/components/Return.vue'

const orderInfo = ref({})
const showPhotoDialog = ref(false)
const currentAction = ref('')
const photoList = ref([])
const remarks = ref('')
const headerPaddingTop = ref(0)

// 状态文本映射
const statusTextMap = {
  '0': '待接单',
  '1': '商家已接单',
  '2': '待取餐',
  '3': '配送中',
  '4': '已完成',
  '5': '待评价',
  '6': '已取消',
  '7': '退款中',
  '8': '退款完成',
  '9': '订单已取消',
}

const statusDescMap = {
  '0': '等待骑手接单',
  '1': '商家正在准备',
  '2': '请前往商家取餐',
  '3': '正在配送中',
  '4': '订单已完成',
  '5': '等待用户评价',
  '6': '订单已取消',
  '7': '正在处理退款',
  '8': '退款已完成',
  '9': '订单已关闭',
}

// 计算内容区高度
const calcContentHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  headerPaddingTop.value = menuButtonInfo.bottom + 20
  // #endif
}

// 获取状态文本
const getStatusText = (status) => {
  return statusTextMap[status] || '未知状态'
}

const getStatusDesc = (status) => {
  return statusDescMap[status] || ''
}

// 是否显示操作按钮
const showActions = computed(() => {
  return [ '3'].includes(orderInfo.value.status)
})

// 获取订单详情
const getOrderDetail = async (orderId) => {
  try {
    const res = await Fetch(`shopping/orderInfo/getOrderInfoAndGoods/${orderId}`, {
      method: 'GET'
    })

    if (res.data.code === 200) {
      orderInfo.value = res.data.data
    } else {
      uni.showToast({
        title: res.data.message || '获取订单详情失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 复制订单号
const copyOrderNo = () => {
  uni.setClipboardData({
    data: orderInfo.value.orderNo,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'none'
      })
    }
  })
}

// 联系商家
const contactStore = () => {
  if (orderInfo.value.storePhone) {
    uni.makePhoneCall({
      phoneNumber: orderInfo.value.storePhone,
      fail: () => {
        uni.showToast({
          title: '拨打电话失败',
          icon: 'none'
        })
      }
    })
  }
}

// 联系顾客
const contactCustomer = () => {
  if (orderInfo.value.deliveryPhone) {
    uni.makePhoneCall({
      phoneNumber: orderInfo.value.deliveryPhone,
      fail: () => {
        uni.showToast({
          title: '拨打电话失败',
          icon: 'none'
        })
      }
    })
  }
}

// 接单
const takeOrder = async () => {
  try {
    const result = await Fetch(`shopping/riderOrders/acceptOrder`, {
      method: 'GET',
      data: { orderId: orderInfo.value.orderId }
    })

    if (result.data.code === 200) {
      uni.showToast({
        title: '接单成功',
        icon: 'success'
      })
      getOrderDetail(orderInfo.value.orderId)
    } else {
      uni.showToast({
        title: result.data.message || '接单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '接单失败',
      icon: 'none'
    })
  }
}

// 开始取餐
const startDelivery = () => {
  currentAction.value = 'pickup'
  photoList.value = []
  remarks.value = ''
  showPhotoDialog.value = true
}

// 确认送达
const confirmDelivery = () => {
  currentAction.value = 'delivery'
  photoList.value = []
  remarks.value = ''
  showPhotoDialog.value = true
}

// 拍照
const handleTakePhoto = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]

      uni.showLoading({ title: '上传中...' })

      try {
        // 这里需要根据你的上传接口调整
        const uploadResult = await uploadImage(tempFilePath)
        photoList.value.push({
          localPath: tempFilePath,
          serverUrl: uploadResult.url
        })
      } catch (error) {
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  })
}

// 提交凭证
const submitPhotoAndRemarks = async () => {
  const photoUrls = photoList.value.map(photo => photo.serverUrl).filter(Boolean)

  try {
    const apiUrl = currentAction.value === 'pickup'
      ? `shopping/riderOrders/takeMealOrder`
      : `shopping/riderOrders/completeOrder`

    const result = await Fetch(apiUrl, {
      method: 'POST',
      data: {
        imgUrl: photoUrls.join(','),
        remark: remarks.value,
        orderId: orderInfo.value.orderId
      }
    })

    if (result.data.code === 200) {
      showPhotoDialog.value = false
      uni.showToast({
        title: currentAction.value === 'pickup' ? '已开始配送' : '配送完成',
        icon: 'success'
      })
      getOrderDetail(orderInfo.value.orderId)
    } else {
      uni.showToast({
        title: result.data.message || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

// 上传图片函数（需要根据实际情况实现）
const uploadImage = async (filePath) => {
  // 这里实现图片上传逻辑
  return { url: filePath } // 临时返回
}
const formatPhoneNumber = (phone) => {
  if (!phone || phone.length < 7) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}
const isPhone = ref(true) // 是否从接单列表进入，是就隐藏号码****

onLoad((options) => {
  console.log(options.orderId,'options.orderId');
  console.log(options.activeIndex,'options.activeIndex');
  if (options.activeIndex == '0') {
    isPhone.value = false
  } else {
    isPhone.value = true
  }
  if (options.orderId) {
    getOrderDetail(options.orderId)
  } else {
    uni.showToast({
      title: '订单ID不存在',
      icon: 'none'
    })
  }
  calcContentHeight()
})
</script>

<style lang="scss" scoped>
.rider-order-detail {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.status-header {
  background: linear-gradient(135deg, #4477c8 0%, #6699ff 100%);
  color: white;
  padding: 40rpx 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-info {
  .status-text {
    font-size: 36rpx;
    font-weight: 600;
    margin-bottom: 8rpx;
  }

  .status-desc {
    font-size: 26rpx;
    opacity: 0.9;
  }
}

.order-amount {
  font-size: 40rpx;
  font-weight: 700;
}

.order-basic, .shop-info, .delivery-info, .goods-info {
  background: white;
  margin: 16rpx 24rpx;
  border-radius: 16rpx;
  padding: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }

  .label {
    font-size: 28rpx;
    color: #666;
    width: 160rpx;
    flex-shrink: 0;
  }

  .value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    margin-right: 16rpx;

    &.pickup-code {
      color: #4477c8;
      font-weight: 600;
    }

    &.text-ellipsis {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }

  .copy-btn {
    padding: 8rpx 16rpx;
    background: #f0f4ff;
    color: #4477c8;
    border-radius: 8rpx;
    font-size: 24rpx;
    flex-shrink: 0;
  }
}

.shop-card {
  display: flex;
  align-items: center;

  .shop-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 12rpx;
    margin-right: 16rpx;
  }

  .shop-detail {
    flex: 1;

    .shop-name {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 8rpx;
    }

    .shop-address {
      font-size: 26rpx;
      color: #666;
    }
  }

  .contact-btn {
    width: 64rpx;
    height: 64rpx;
    background: #4477c8;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
  }
}

.address-card {
  .address-item {
    display: flex;
    align-items: flex-start;
    padding: 20rpx 0;
  }

  .address-line {
    width: 2rpx;
    height: 40rpx;
    background: #ddd;
    margin-left: 16rpx;
  }
}

.address-tag {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  font-weight: 600;
  color: #fff;
  margin-right: 16rpx;
  flex-shrink: 0;

  &.pickup-tag {
    background: #4477c8;
  }

  &.delivery-tag {
    background: #ff6b6b;
  }
}

.address-content {
  flex: 1;

  .customer-name {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 8rpx;
  }

  .address-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.4;
    margin-bottom: 8rpx;
  }

  .customer-phone {
    font-size: 26rpx;
    color: #4477c8;
  }
}

.goods-list {
  .goods-item {
    display: flex;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }
  }

  .goods-image {
    width: 80rpx;
    height: 80rpx;
    border-radius: 8rpx;
    margin-right: 16rpx;
  }

  .goods-detail {
    flex: 1;

    .goods-name {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 8rpx;
    }

    .goods-spec {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 8rpx;
    }

    .goods-priceStr {
      font-size: 26rpx;
      color: #ff4757;
      font-weight: 600;
    }
  }
}

.fee-summary {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f5f5f5;

  .fee-row {
    display: flex;
    justify-content: space-between;
    padding: 8rpx 0;

    &.total {
      font-weight: 600;
      font-size: 30rpx;
      color: #ff4757;
      border-top: 1rpx solid #f5f5f5;
      margin-top: 8rpx;
      padding-top: 16rpx;
    }
  }

  .fee-label {
    font-size: 26rpx;
    color: #666;
  }

  .fee-value {
    font-size: 26rpx;
    color: #333;
  }
}

.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx 24rpx;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 16rpx;
}

.action-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;

  &.primary {
    background: #4477c8;
    color: white;
  }

  &.secondary {
    background: #f5f5f5;
    color: #666;
  }
}

// 弹窗样式保持与原页面一致
.photo-dialog {
  width: 650rpx;
  border-radius: 20rpx;
  background-color: #fff;
  padding: 30rpx;

  .dialog-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .photo-area {
    margin-bottom: 30rpx;

    .photo-list {
      display: flex;
      flex-wrap: wrap;

      .photo-item {
        width: 180rpx;
        height: 180rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;

        image {
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
        }
      }

      .photo-add {
        width: 180rpx;
        height: 180rpx;
        background-color: #f5f5f5;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #666;

        .iconfont {
          font-size: 48rpx;
          margin-bottom: 10rpx;
        }
      }
    }
  }

  .remarks-area {
    margin-bottom: 30rpx;

    .remarks-input {
      width: 100%;
      height: 150rpx;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      padding: 20rpx;
      box-sizing: border-box;
      font-size: 28rpx;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;

    button {
      width: 280rpx;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .btn-cancel {
      background-color: #E0E0E0;
      color: #191919;
    }

    .btn-submit {
      background-color: #4477c8;
      color: white;
      font-weight: bold;
    }
  }
}
</style>
